package com.yejiali.backend.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.yejiali.backend.entity.Messages;
import com.yejiali.backend.entity.vo.SendMsPersonsVO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 消息表(Messages)表数据库访问层
 *
 * @author yejiali
 * @since 2025-08-18 17:10:53
 */
@Mapper
public interface MessagesMapper extends BaseMapper<Messages> {
    /**
     * 查询发送消息的人员ID、最近消息内容及发送时间
     * @param receiverId 接收者ID（当前用户）
     * @return 发送者列表
     */
    @Select("SELECT " +
            "m.sender_id as userId, " +
            "u.nickname as nickName, " +
            "u.avatar as avatar, " +
            "m.content as lastMessage, " +
            "m.send_time as sendTime " +
            "FROM messages m " +
            "INNER JOIN ( " +
            "    SELECT sender_id, MAX(send_time) as latest_time " +
            "    FROM messages " +
            "    WHERE receiver_id = #{receiverId} AND is_deleted = 0 " +
            "    GROUP BY sender_id " +
            ") latest ON m.sender_id = latest.sender_id AND m.send_time = latest.latest_time " +
            "INNER JOIN users u ON m.sender_id = u.user_id " +
            "WHERE m.receiver_id = #{receiverId} AND m.is_deleted = 0 " +
            "ORDER BY m.send_time DESC")
    List<SendMsPersonsVO> selectSendPersons(@Param("receiverId") Long receiverId);
}

